package com.leyou.user.controller;

import com.leyou.user.pojo.User;
import com.leyou.user.service.UserService;
import com.sun.org.apache.xpath.internal.operations.Bool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.bind.BindResult;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.stream.Collectors;

/**
 * @author huangxin
 * @date 2019/5/11-10:52
 */
@RestController
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 验证用户名或手机号是否存在
     * @param data
     * @param type
     * @return
     */
    @GetMapping("check/{data}/{type}")
    public ResponseEntity<Boolean>checkData(@PathVariable("data") String data, @PathVariable("type")Integer type){
        return ResponseEntity.ok(userService.checkData (data,type));
    }


    @PostMapping("register")
    public ResponseEntity<Void> register(@Valid User user, BindingResult result, @RequestParam("code") String code){
        //自己处理异常
//        if (result.hasFieldErrors()){
//            throw  new RuntimeException(
//                    result.getAllErrors().stream()
//                            .map(e->e.getDefaultMessage()).collect(Collectors.joining("\n")));
//        }
        userService.register(user,code);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    /**
     * 发送验证码
     * @param phone
     * @return
     */
    @PostMapping("code")
    public ResponseEntity<Void> sendCode(@RequestParam("phone") String phone){
        userService.sendCode(phone);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

    @GetMapping("query")
    public ResponseEntity<User> query(@RequestParam("username") String username,@RequestParam("password")String password){
        return ResponseEntity.ok(userService.query (username,password));
    }
}
